package com.ksyun.campus.metaserver.zk;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ksyun.campus.metaserver.domain.DataServerInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * ZooKeeper数据清理工具
 * 用于清理无效的DataServer数据
 */
@Slf4j
@Component
public class ZooKeeperCleanupTool implements CommandLineRunner {
    
    @Value("${minfs.zookeeper.connection-string:127.0.0.1:2181}")
    private String zkConnectionString;
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    public void run(String... args) throws Exception {
        // 只在需要时启用清理功能
        if (System.getProperty("cleanup.zk") != null) {
            cleanupInvalidDataServerData();
        }
    }
    
    /**
     * 主方法，用于独立运行清理工具
     */
    public static void main(String[] args) {
        ZooKeeperCleanupTool tool = new ZooKeeperCleanupTool();
        tool.zkConnectionString = "127.0.0.1:2181"; // 默认值
        tool.cleanupInvalidDataServerData();
    }
    
    /**
     * 清理无效的DataServer数据
     */
    public void cleanupInvalidDataServerData() {
        log.info("Starting ZooKeeper cleanup...");
        
        CuratorFramework curator = null;
        try {
            curator = CuratorFrameworkFactory.builder()
                    .connectString(zkConnectionString)
                    .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                    .build();
            curator.start();
            
            String dataServerPath = "/minfs/ds/instances";
            
            if (curator.checkExists().forPath(dataServerPath) != null) {
                List<String> children = curator.getChildren().forPath(dataServerPath);
                
                for (String child : children) {
                    String childPath = dataServerPath + "/" + child;
                    try {
                        byte[] data = curator.getData().forPath(childPath);
                        if (data != null) {
                            String dataStr = new String(data, StandardCharsets.UTF_8);
                            
                            // 尝试解析为JSON
                            try {
                                objectMapper.readValue(dataStr, DataServerInfo.class);
                                log.debug("Valid DataServer data found: {}", child);
                            } catch (Exception e) {
                                log.warn("Invalid DataServer data found, removing: {} (data: {})", child, dataStr);
                                curator.delete().forPath(childPath);
                            }
                        }
                    } catch (Exception e) {
                        log.error("Error processing child {}: {}", child, e.getMessage());
                    }
                }
            }
            
            log.info("ZooKeeper cleanup completed");
            
        } catch (Exception e) {
            log.error("Error during ZooKeeper cleanup", e);
        } finally {
            if (curator != null) {
                curator.close();
            }
        }
    }
}
